const functionJS = {

    /**
 * 加权随机选择
 * @param {number[]} probArr - 概率数组，和应为1
 * @param {any[]} valueArr - 对应的值数组，长度和概率数组一致
 * @returns {any} 选中的值
 */
    weightedRandom(probArr, valueArr) {
        // 先计算累计概率数组
        let cumulative = [];
        probArr.reduce((sum, val, i) => cumulative[i] = sum + val, 0);

        // 生成0~1之间的随机数
        let rand = Math.random();

        // 找到rand落在哪个区间
        for (let i = 0; i < cumulative.length; i++) {
            if (rand < cumulative[i]) {
                return valueArr[i];
            }
        }

        // 万一浮点误差导致没有返回，默认返回最后一个
        return valueArr[valueArr.length - 1];
    },

    //格式化ip
    normalizeIP(ip) {
        if (ip.startsWith('::ffff:')) {
            return ip.replace('::ffff:', '');
        }
        return ip;
    },


    //广播某个玩家的邮件
    broadcastPlayerMail(clients, playerId, mailList, isRecharge = false) {
        let ws = clients.get(playerId);
        if (!ws) {
            playerId = parseInt(playerId);
            ws = clients.get(playerId);
        }
        if (ws && ws.readyState === ws.OPEN) {
            ws.send(JSON.stringify({
                action: 'newMail',
                data: mailList,
                ...(isRecharge ? { isRecharge: true } : {})
            }));
        }
    }

}

module.exports = functionJS;